import React from "react";
import ReactDOM from "react-dom";
import Tools from "../../lib/tools";
import AJAX from "../../lib/ajax";
import { addErrorListener } from "../../lib/handleError"
import weixinShare from "../../lib/weixinShare";

require('../../lib/rem')
require('./MyPackageDeliveryDetail.less')
require('../../styles/common.less')

const SendOffCard = require('../../components/SendOffCard')
const FormView = require('../MyPackage/components/FormView')
const Pay = require('../MyPackage/components/Pay')
const Evaluation = require('../MyPackage/components/Evaluation')
const DialogAdress = require('../MyPackage/components/DialogAdress')
const ServiceEvaluation = require('../MyPackage/components/ServiceEvaluation')
const Dialog = require('../MyPackage/components/Dialog')

class App extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            url_params: Tools.getParams(),
            score: 0,
            show: false,
            order_detail: [],
            form_data: [],
            express_form_data: [],
            evaluation_data: {},
            pay_data: {},
            confirm_data: {}
        }
    }

    componentWillMount() {
        addErrorListener()()
        weixinShare.hideAll()
        const url_params = this.state.url_params
        this.load()
    }

    componentDidMount() {
        //埋点 百度统计
        AJAX.appendBaiduAnalysis()
    }

    //订单信息卡片
    detail() {
        if (this.state.order_detail.length === 0) {
            return null
        } else {
            const delivery_cards = this.state.order_detail.map((item, index) => {
                item.info_tips = true;  //状态显示
                item.btn_show = false;  //按钮显示
                item.icon_show = true
                return (
                    <SendOffCard dataSource={item} key={`delivery_card_${index}`} onClick={this.jumpDeliveryDetail()} />
                )
            })
            return (
                <div className="detail-top-border detail-bottom-border mt10">
                    {delivery_cards}
                </div>
            )
        }
    }

    jumpDeliveryDetail() {
        return () => {
            const { url_params } = this.state
            const order_id = url_params.order_id
            const type = url_params.type
            const url = `./MyPackageTracking?order_id=${order_id}&type=${type}&page_type=delivery`

            window.location.href = url
        }
    }

    //删除订单
    delete() {
        const url_params = this.state.url_params
        Dialog.confirm({
            title: "删除订单",
            content: "确认删除订单吗",
            okText: "确认",
            cancelText: "取消",
            onOK: () => {
                AJAX.request("sending_order_delete", {
                    order_id: this.state.order_id,
                    type: url_params.type || 1
                }, (data) => {
                    window.location.href = "./MyPackage"
                })
            },
            onCancel: () => {
            }
        })
    }

    //取消订单
    cancel() {
        const url_params = this.state.url_params
        Dialog.confirm({
            title: "",
            content: "请确认取消订单！",
            okText: "确认",
            cancelText: "取消",
            onOK: () => {
                AJAX.request("sending_order_cancel", {
                    order_id: this.state.order_id,
                    type: url_params.type || 1
                }, (data) => {
                    this.load()
                })
            },
            onCancel: () => {
            }
        })
    }

    deleteOrder(data) {
        return (
            <div className="delete-order">
                <a href="javascript:;" className="weui-btn weui-btn_plain-orange"
                    onClick={this.delete.bind(this)}
                >删除订单</a>
            </div>
        )
    }

    cancelOrder(data) {
        return (
            <div className="delete-order">
                <a href="javascript:;" className="weui-btn weui-btn_plain-orange"
                    onClick={this.cancel.bind(this)}
                >取消订单</a>
            </div>
        )
    }

    //快递投递
    deliveryOrder() {
        const url_params = this.state.url_params
        return (
            <div className="delete-order flex">
                <a href={"./CabinetSendingDeliver?open_cabinet_type=1&order_id=" + url_params.order_id + "&cabinet_code=" + this.state.order_detail[0].cabinet_code}
                    className="weui-btn weui-btn_plain-orange flex1"
                >投递</a>
                <a href="javascript:;" className="weui-btn weui-btn_plain-orange flex1"
                    onClick={this.cancel.bind(this)}
                >取消订单</a>
            </div>
        )
    }

    //取回快递
    getBackOrder() {
        const url_params = this.state.url_params
        return (
            <div className="delete-order">
                <a href={"./CabinetSendingDeliver?open_cabinet_type=2&order_id=" + url_params.order_id + "&cabinet_code=" + this.state.order_detail[0].cabinet_code}
                    className="weui-btn weui-btn_plain-orange"
                >取回快递</a>
            </div>
        )
    }

    translateOrderCard(data) {
        let flag_type, btn_type
        switch (data.status) {
            case 100:
                flag_type = "AlreadyOrder"
                btn_type = "CancelOrder"
                break
            case 101:
            case 110:
                flag_type = "WaitPay"
                btn_type = "Pay"
                break
            case 120:
                flag_type = "AlreadyStart"
                btn_type = "Evalute"
                break
            case 130:
                flag_type = "OnDistributing",
                    btn_type = "Evalute"
                break
            case 140:
                flag_type = "AlreadySign",
                    btn_type = "Evalute"
                break
            case 150:
                flag_type = "AlreadyCancel",
                    btn_type = "DeleteRecord"
        }
        return {
            type: "DETAIL",
            flag_type: flag_type,
            order: data.id,
            order_num: data.order_num,
            from_city: data.sender_addr.area_name,
            to_city: data.consignee_addr.area_name,
            from_name: data.sender_addr.realname,
            to_name: data.consignee_addr.realname,
            log_info: data.desc_content,
            log_time: data.desc_time,
            send_type_desc: data.send_type_desc,
            send_type: data.send_type,  //寄件方式 1:网点  2:柜体
            status_list: data.status_list,  //str 寄件方式描述(服务网点寄件、智能柜寄件),
            cabinet_code: data.cabinet_code,    //柜体编号
        }
    }

    translateExpressFormData(data, status) {
        let form_list = []
        if (data.cancel_reason) {
            form_list.push({
                className: 'textRed',
                label: "退回原因",
                span: `${data.cancel_reason}`
            })
        }
        if (data.courier_phone) {
            form_list.push({
                label: "快递公司",
                span: `${data.express_name}`
            }, {
                label: "联系电话",
                span: `${data.courier_phone}`
            })
        }
        return form_list
    }

    translateFormData(data, status) {
        let pay_data = `应付${data.fee / 100}元，实付${data.real_fee / 100}元`
        if (status === 100 || status === 110 || status === 150 && !data.real_fee) {
            pay_data = `应付${data.fee / 100}元`
        }
        let pkg_data = `${data.pkg_type}`
        if (data.weight) {
            pkg_data = `${data.pkg_type}，${data.weight / 1000}KG`
        }
        let form_data = [{
            label: "托寄物",
            span: pkg_data
        },
        {
            label: "保价金额",
            span: `价值${data.evaluation / 100}元，保费${data.insure_fee / 100}元`
        },
        // 服务网点寄件不 render 下面两行
        {
            label: data.send_type == 2 ? "设备名称" : null,
            span: data.send_type == 2 ? `${data.cabinet_name}` : null
        },
        {
            label: data.send_type == 2 ? "设备编号" : null,
            span: data.send_type == 2 ? `${data.cabinet_code}` : null
        },
        {
            label: "付款方式",
            span: `${data.pay_side}`
        },
        {
            label: "寄件方式",
            span: `${data.send_type_desc}`
        },
        {
            //没有快递单号则不 render 该行
            label: data.exp_code ? '快递单号' : null,
            span: `${data.exp_code}`,
        },
        {
            label: "付款信息",
            span: pay_data
        },
        {
            label: "下单时间",
            span: `${data.create_time}`
        }]
        return form_data
    }

    translateAddressData(data) {
        return {
            recipent_name: data.consignee_addr.realname,
            recipent_address: data.consignee_addr.address,
            recipent_phone: data.consignee_addr.phone,
            delivery_name: data.sender_addr.realname,
            delivery_address: data.sender_addr.address,
            delivery_phone: data.sender_addr.phone,
        }
    }

    translatePayData(data) {
        console.log("data: ", data)
        return {
            //是否显示余额支付，柜体寄件不显示 (//寄件方式 1:网点  2:柜体)
            //寄件不支持余额，因为可能会倒贴
            yue_show: data.send_type == 2 ? false : true,
            order_id: this.state.order_id,
            type: data.type,
            real_fee: data.real_fee,
            coupon_reason_id: data.coupon_reason_id,
            coupon_remark: data.coupon_remark,
            callback: this.load.bind(this)
        }
    }

    //确认关箱参数转换
    translateConfirmData(data) {
        return {
            order_id: data.id, //订单id
            cabinet_code: data.cabinet_code, //柜体编号
            cell_id: data.cell_id,    //格口id
        }
    }

    translateEvaluationData(data) {
        let mode
        if (data.star === 5 && !data.comment_content) {
            //五星评分，无评价内容，无需回复
            mode = "NoComment"
        } else if (data.star < 5 && !data.comment_content) {
            //低于五分，无评价内容，无需回复
            mode = "NoReply"
        } else {
            //其他情况，需要回复
            mode = "HaveReply"
        }
        return {
            mode,
            type: data.type,
            comment: data.comment_content,
            score: data.star,
            reply: data.feedback_content,
            callback: this.load
        }
    }

    load() {
        const url_params = this.state.url_params
        this.setState({
            order_id: url_params.order_id
        })
        AJAX.request("sending_order_detail", {
            order_id: url_params.order_id,
            aditem_id: url_params.aditem_id,
            type: url_params.type || 1
        }, (data) => {
            const order_card = this.translateOrderCard(data.body)
            const express_form_data = this.translateExpressFormData(data.body)
            const form_data = this.translateFormData(data.body, data.body.status)
            const address_data = this.translateAddressData(data.body)
            const confirm_data = this.translateConfirmData(data.body)   //确认关箱参数转换
            let pay_data = {}, evaluation_data = {}, can_evaluate, can_cancel, can_delete, can_getBack, can_delivery, should_confirm
            if (data.body.status === 100) {
                //已下单，此时可以取消订单
                can_cancel = true
                //柜体寄件，此时可投递
                can_delivery = data.body.type == 3 ? true : false
                should_confirm = data.body.type == 3 && data.body.cell_id ? true : false
            } else if (data.body.status === 110) {
                //待支付,
                pay_data = this.translatePayData(data.body)
                //柜体寄件此时可以取消订单
                can_cancel = data.body.type == 3 ? true : false
            } else if (data.body.status === 120) {
                //已支付，已接单，柜体寄件此时可以取消订单
                can_cancel = data.body.type == 3 ? true : false
            } else if (data.body.status === 125) {
                //待取回，快递可取回
                can_getBack = true
            } else if (data.body.status === 150) {
                //已取消，可以删除
                can_delete = true
            }
            if (data.body.can_comment === 1) {
                //可以评论
                can_evaluate = true
            } else {
                if (data.body.star > 0) {
                    //不可评论，已经评论过了，需要显示评论
                    evaluation_data = this.translateEvaluationData(data.body)
                }
            }

            //快递取回 地址带有柜体编号cabinet_code即为快递取回操作中
            //来自于扫描设备编号页面，扫描完需要取回件则进入当前页面
            if (url_params.cabinet_code) {
                AJAX.request("get_back", {
                    order_id: url_params.order_id,
                    cabinet_code: url_params.cabinet_code,
                }, data => {
                    if (data.code == 0) {
                        Dialog.info({
                            title: "",
                            content: "箱门" + data.body.cell_desc + "已开，请取回快递！取回快递后，请将箱门关闭！",
                            okText: "知道了",
                            onOK: () => {
                                const wx_type = window.localStorage.getItem('wx_type');
                                window.location.href = `./PickUp?wx_type=${wx_type}`;   //返回首页
                            }
                        })
                    }
                })

            }

            this.setState({
                order_detail: [order_card],
                express_form_data,
                form_data,
                address_data,
                pay_data,
                can_evaluate,
                can_cancel,
                can_delete,
                can_getBack,
                can_delivery,
                evaluation_data,
                confirm_data,   //确认关箱参数
                should_confirm  //确认关箱提示
            })
        })
    }

    render() {
        const {
            url_params,
            order_id,
            address_data,
            order_detail,
            express_form_data,  // 订单退回原因，1.系统退回，2.用户取消，3.快递员拒绝揽件
            form_data,          // 订单基础信息
            can_delivery,       // 显示投递按钮
            can_getBack,        // 显示取回按钮
            evaluation_data,    // 显示已评论的内容，依赖 can_cancel
            can_cancel,         // 是否可以取消订单
            can_evaluate,       // 显示待评价按钮，依赖 can_cancel
            can_delete,         // 显示删除订单
            pay_data,           // 显示支付按钮，依赖 can_cancel
            should_confirm,     // 如果之前用户没有点关箱，此时必须他点确认
            confirm_data,       // 确认关箱的参数
        } = this.state

        //快递投递
        const delivery = can_delivery
            ? this.deliveryOrder()
            : null

        //取回快递
        const get_back = can_getBack
            ? this.getBackOrder()
            : null

        //评价
        const service_evaluation = Object.keys(evaluation_data).length > 0
            ? <div className="detail-bottom-border mt10 mb10">
                <ServiceEvaluation
                    dataSource={evaluation_data}
                    can_cancel={can_cancel}
                    this={this}
                    cancel={this.cancel}>
                </ServiceEvaluation>
            </div>
            : null

        //评价 Dialog
        const evaluation = can_evaluate
            ? <Evaluation
                orderId={order_id}
                type={url_params.type}
                this={this}
                can_cancel={can_cancel}
                cancel={this.cancel}
                callback={this.load.bind(this)} />
            : null

        //取消订单
        const cancel_order = can_cancel
            ? this.cancelOrder()
            : null

        //删除订单
        const delete_order = can_delete
            ? this.deleteOrder()
            : null

        //支付 Dialog
        const pay = Object.keys(pay_data).length > 0
            ? <Pay
                dataSource={pay_data}
                can_cancel={can_cancel}
                this={this}
                cancel={this.cancel} />
            : null

        //订单退回原因，1.系统退回，2.用户取消，3.快递员拒绝揽件
        const express_form_view = express_form_data.length > 0
            ? <div className="detail-top-border detail-bottom-border mt10">
                <FormView dataSource={express_form_data} />
            </div>
            : null

        //订单描述信息
        const form_view = form_data.length > 0
            ? <div className="detail-top-border detail-bottom-border mt10">
                <FormView dataSource={form_data} />
            </div>
            : null

        //确认关箱
        const cabinet_close_confirm = should_confirm
            ? Dialog.info({
                title: "",
                content: "已有快递放入格口，请确认关箱。",
                okText: "确认",
                onOK: () => {
                    //  确认投递
                    AJAX.request("confirm_delivery", {
                        order_id: confirm_data.order_id, //订单id
                        cabinet_code: confirm_data.cabinet_code, //柜体编号
                        cell_id: confirm_data.cell_id,    //格口id
                    }, data => {
                        if (data.code == 0) {
                            //确认成功－－－重新刷新当前页面
                            window.location.href = "./MyPackageDeliveryDetail?order_id=" + confirm_data.order_id + "&type=3";  //返回首页
                        }
                    })
                }
            })
            : null

        return (
            cabinet_close_confirm ? cabinet_close_confirm :
                <div >
                    {/* 必要区域 */}
                    <DialogAdress dataSource={address_data} />
                    {this.detail()}
                    {express_form_view}
                    {form_view}
                    {/* 互斥区域 */}
                    {service_evaluation}
                    {evaluation}
                    {pay}
                    {delivery}
                    {get_back}
                    {order_detail.length > 0
                        && order_detail[0].send_type == 1
                        && cancel_order}
                    {order_detail.length > 0
                        && order_detail[0].send_type == 2
                        && !evaluation
                        && !service_evaluation
                        && !pay
                        && !delivery
                        && cancel_order
                    }
                    {delete_order}
                </div>
        )
    }
}
ReactDOM.render(<App />, document.getElementById('app'))
if (module.hot) {
    module.hot.accept();
}